
<!DOCTYPE html
  PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   
      <title>第&nbsp;5&nbsp;章&nbsp;对象和面向对象</title>
      <link rel="stylesheet" href="../diveintopython.css" type="text/css">
      <link rev="made" href="mailto:f8dy@diveintopython.org">
      <meta name="generator" content="DocBook XSL Stylesheets V1.52.2">
      <meta name="keywords" content="Python, Dive Into Python, tutorial, object-oriented, programming, documentation, book, free">
      <meta name="description" content="Python from novice to pro">
      <link rel="home" href="../toc/index.html" title="Dive Into Python">
      <link rel="up" href="../toc/index.html" title="Dive Into Python">
      <link rel="previous" href="../power_of_introspection/summary.html" title="4.9.&nbsp;小结">
      <link rel="next" href="importing_modules.html" title="5.2.&nbsp;使用 from module import 导入模块">
   </head>
   <body>
      <table id="Header" width="100%" border="0" cellpadding="0" cellspacing="0" summary="">
         <tr>
            <td id="breadcrumb" colspan="5" align="left" valign="top">导航：<a href="../index.html">起始页</a>&nbsp;&gt;&nbsp;<a href="../toc/index.html">Dive Into Python</a>&nbsp;&gt;&nbsp;<span class="thispage">对象和面向对象</span></td>
            <td id="navigation" align="right" valign="top">&nbsp;&nbsp;&nbsp;<a href="../power_of_introspection/summary.html" title="上一页: “小结”">&lt;&lt;</a>&nbsp;&nbsp;&nbsp;<a href="importing_modules.html" title="下一页: “使用 from module import 导入模块”">&gt;&gt;</a></td>
         </tr>
         <tr>
            <td colspan="3" id="logocontainer">
               <h1 id="logo"><a href="../index.html" accesskey="1">深入 Python :Dive Into Python 中文版</a></h1>
               <p id="tagline">Python 从新手到专家 [Dip_5.4b_CPyUG_Release]</p>
            </td>
            <td colspan="3" align="right">
               <form id="search" method="GET" action="http://www.google.com/custom">
                  <p><label for="q" accesskey="4">Find:&nbsp;</label><input type="text" id="q" name="q" size="20" maxlength="255" value=""> <input type="submit" value="搜索"><input type="hidden" name="domains" value="woodpecker.org.cn/diveintopython"><input type="hidden" name="sitesearch" value="www.woodpecker.org.cn/diveintopython"></p>
               </form>
            </td>
         </tr>
      </table>
      <!--#include virtual="/inc/ads" -->
      <div class="chapter" lang="zh_cn">
         <div class="titlepage">
            <div>
               <div>
                  <h2 class="title"><a name="fileinfo"></a>第&nbsp;5&nbsp;章&nbsp;对象和面向对象
                  </h2>
               </div>
            </div>
            <div></div>
         </div>
         <div class="toc">
            <ul>
               <li><span class="section"><a href="index.html#fileinfo.divein">5.1. 概览</a></span></li>
               <li><span class="section"><a href="importing_modules.html">5.2. 使用 from module import 导入模块</a></span></li>
               <li><span class="section"><a href="defining_classes.html">5.3. 类的定义</a></span><ul>
                     <li><span class="section"><a href="defining_classes.html#d0e11869">5.3.1. 初始化并开始类编码</a></span></li>
                     <li><span class="section"><a href="defining_classes.html#d0e12045">5.3.2. 了解何时去使用 self 和 __init__</a></span></li>
                  </ul>
               </li>
               <li><span class="section"><a href="instantiating_classes.html">5.4. 类的实例化</a></span><ul>
                     <li><span class="section"><a href="instantiating_classes.html#d0e12314">5.4.1. 垃圾回收</a></span></li>
                  </ul>
               </li>
               <li><span class="section"><a href="userdict.html">5.5. 探索 UserDict：一个封装类</a></span></li>
               <li><span class="section"><a href="special_class_methods.html">5.6. 专用类方法</a></span><ul>
                     <li><span class="section"><a href="special_class_methods.html#d0e13019">5.6.1. 获得和设置数据项</a></span></li>
                  </ul>
               </li>
               <li><span class="section"><a href="special_class_methods2.html">5.7. 高级专用类方法</a></span></li>
               <li><span class="section"><a href="class_attributes.html">5.8. 类属性介绍</a></span></li>
               <li><span class="section"><a href="private_functions.html">5.9. 私有函数</a></span></li>
               <li><span class="section"><a href="summary.html">5.10. 小结</a></span></li>
            </ul>
         </div>
         <div class="abstract">
            <p>这一章，和此后的许多章，均讨论了面向对象的 <span class="application">Python</span> 程序设计。
            </p>
         </div>
         <div class="section" lang="zh_cn">
            <div class="titlepage">
               <div>
                  <div>
                     <h2 class="title"><a name="fileinfo.divein"></a>5.1.&nbsp;概览
                     </h2>
                  </div>
               </div>
               <div></div>
            </div>
            <div class="abstract">
               <p>下面是一个完整的，可运行的 <span class="application">Python</span> 程序。请阅读模块、类和函数的 <a href="../getting_to_know_python/documenting_functions.html" title="2.3.&nbsp;文档化函数"><tt class="literal">doc string</tt>s</a>，可以大概了解这个程序所做的事情和工作情况。像平时一样，不用担心你不理解的东西，这就是本章其它部分将告诉你的内容。
               </p>
            </div>
            <div class="example"><a name="d0e11326"></a><h3 class="title">例&nbsp;5.1.&nbsp;<tt class="filename">fileinfo.py</tt></h3>
               <p>如果您还没有下载本书附带的样例程序, 可以 <a href="http://www.woodpecker.org.cn/diveintopython/download/diveintopython-exampleszh-cn-5.4b.zip" title="Download example scripts">下载本程序和其他样例程序</a>。
               </p><pre class="programlisting">
<span class='pystring'>"""Framework for getting filetype-specific metadata.

Instantiate appropriate class with filename.  Returned object acts like a
dictionary, with key-value pairs for each piece of metadata.
    import fileinfo
    info = fileinfo.MP3FileInfo("/music/ap/mahadeva.mp3")
    print "\\n".join(["%s=%s" % (k, v) for k, v in info.items()])

Or use listDirectory function to get info on all files in a directory.
    for info in fileinfo.listDirectory("/music/ap/", [".mp3"]):
        ...

Framework can be extended by adding classes for particular file types, e.g.
HTMLFileInfo, MPGFileInfo, DOCFileInfo.  Each class is completely responsible for
parsing its files appropriately; see MP3FileInfo for example.
"""</span>
<span class='pykeyword'>import</span> os
<span class='pykeyword'>import</span> sys
<span class='pykeyword'>from</span> UserDict <span class='pykeyword'>import</span> UserDict

<span class='pykeyword'>def</span><span class='pyclass'> stripnulls</span>(data):
    <span class='pystring'>"strip whitespace and nulls"</span>
    <span class='pykeyword'>return</span> data.replace(<span class='pystring'>"\00"</span>, <span class='pystring'>""</span>).strip()

<span class='pykeyword'>class</span><span class='pyclass'> FileInfo</span>(UserDict):
    <span class='pystring'>"store file metadata"</span>
    <span class='pykeyword'>def</span><span class='pyclass'> __init__</span>(self, filename=None):
        UserDict.__init__(self)
        self[<span class='pystring'>"name"</span>] = filename

<span class='pykeyword'>class</span><span class='pyclass'> MP3FileInfo</span>(FileInfo):
    <span class='pystring'>"store ID3v1.0 MP3 tags"</span>
    tagDataMap = {<span class='pystring'>"title"</span>   : (  3,  33, stripnulls),
                  <span class='pystring'>"artist"</span>  : ( 33,  63, stripnulls),
                  <span class='pystring'>"album"</span>   : ( 63,  93, stripnulls),
                  <span class='pystring'>"year"</span>    : ( 93,  97, stripnulls),
                  <span class='pystring'>"comment"</span> : ( 97, 126, stripnulls),
                  <span class='pystring'>"genre"</span>   : (127, 128, ord)}

    <span class='pykeyword'>def</span><span class='pyclass'> __parse</span>(self, filename):
        <span class='pystring'>"parse ID3v1.0 tags from MP3 file"</span>
        self.clear()
        <span class='pykeyword'>try</span>:                               
            fsock = open(filename, <span class='pystring'>"rb"</span>, 0)
            <span class='pykeyword'>try</span>:                           
                fsock.seek(-128, 2)        
                tagdata = fsock.read(128)  
            <span class='pykeyword'>finally</span>:                       
                fsock.close()              
            <span class='pykeyword'>if</span> tagdata[:3] == <span class='pystring'>"TAG"</span>:
                <span class='pykeyword'>for</span> tag, (start, end, parseFunc) <span class='pykeyword'>in</span> self.tagDataMap.items():
                    self[tag] = parseFunc(tagdata[start:end])               
        <span class='pykeyword'>except</span> IOError:                    
            <span class='pykeyword'>pass</span>                           

    <span class='pykeyword'>def</span><span class='pyclass'> __setitem__</span>(self, key, item):
        <span class='pykeyword'>if</span> key == <span class='pystring'>"name"</span> <span class='pykeyword'>and</span> item:
            self.__parse(item)
        FileInfo.__setitem__(self, key, item)

<span class='pykeyword'>def</span><span class='pyclass'> listDirectory</span>(directory, fileExtList):                                        
    <span class='pystring'>"get list of file info objects for files of particular extensions"</span>
    fileList = [os.path.normcase(f)
                <span class='pykeyword'>for</span> f <span class='pykeyword'>in</span> os.listdir(directory)]           
    fileList = [os.path.join(directory, f) 
               <span class='pykeyword'>for</span> f <span class='pykeyword'>in</span> fileList
                <span class='pykeyword'>if</span> os.path.splitext(f)[1] <span class='pykeyword'>in</span> fileExtList] 
    <span class='pykeyword'>def</span><span class='pyclass'> getFileInfoClass</span>(filename, module=sys.modules[FileInfo.__module__]):      
        <span class='pystring'>"get file info class from filename extension"</span>                             
        subclass = <span class='pystring'>"%sFileInfo"</span> % os.path.splitext(filename)[1].upper()[1:]       
        <span class='pykeyword'>return</span> hasattr(module, subclass) <span class='pykeyword'>and</span> getattr(module, subclass) <span class='pykeyword'>or</span> FileInfo
    <span class='pykeyword'>return</span> [getFileInfoClass(f)(f) <span class='pykeyword'>for</span> f <span class='pykeyword'>in</span> fileList]                             

<span class='pykeyword'>if</span> __name__ == <span class='pystring'>"__main__"</span>:
    <span class='pykeyword'>for</span> info <span class='pykeyword'>in</span> listDirectory(<span class='pystring'>"/music/_singles/"</span>, [<span class='pystring'>".mp3"</span>]): <a name="fileinfo_divein.1.1"></a><img src="../images/callouts/1.png" alt="1" border="0" width="12" height="12">
        <span class='pykeyword'>print</span> <span class='pystring'>"\n"</span>.join([<span class='pystring'>"%s=%s"</span> % (k, v) <span class='pykeyword'>for</span> k, v <span class='pykeyword'>in</span> info.items()])
        print</pre><div class="calloutlist">
                  <table border="0" summary="Callout list">
                     <tr>
                        <td width="12" valign="top" align="left"><a href="#fileinfo_divein.1.1"><img src="../images/callouts/1.png" alt="1" border="0" width="12" height="12"></a> 
                        </td>
                        <td valign="top" align="left">这个程序的输入要取决于你硬盘上的文件。为了得到有意义的输出，你应该修改目录路径指向你自已机器上的一个 MP3 文件目录。</td>
                     </tr>
                  </table>
               </div>
            </div>
            <div class="informalexample">
               <p>下面就是从我的机器上得到的输出。你的输出将不一样，除非，由于某些令人吃惊的巧合，你与我有着共同的音乐品味。</p><pre class="screen"><span class="computeroutput">album=
artist=Ghost in the Machine
title=A Time Long Forgotten (Concept
genre=31
name=/music/_singles/a_time_long_forgotten_con.mp3
year=1999
comment=http://mp3.com/ghostmachine

album=Rave Mix
artist=***DJ MARY-JANE***
title=HELLRAISER****Trance from Hell
genre=31
name=/music/_singles/hellraiser.mp3
year=2000
comment=http://mp3.com/DJMARYJANE

album=Rave Mix
artist=***DJ MARY-JANE***
title=KAIRO****THE BEST GOA
genre=31
name=/music/_singles/kairo.mp3
year=2000
comment=http://mp3.com/DJMARYJANE

album=Journeys
artist=Masters of Balance
title=Long Way Home
genre=31
name=/music/_singles/long_way_home1.mp3
year=2000
comment=http://mp3.com/MastersofBalan

album=
artist=The Cynic Project
title=Sidewinder
genre=18
name=/music/_singles/sidewinder.mp3
year=2000
comment=http://mp3.com/cynicproject

album=Digitosis@128k
artist=VXpanded
title=Spinning
genre=255
name=/music/_singles/spinning.mp3
year=2000
comment=http://mp3.com/artists/95/vxp</span></pre></div>
         </div>
      </div>
      <table class="Footer" width="100%" border="0" cellpadding="0" cellspacing="0" summary="">
         <tr>
            <td width="35%" align="left"><br><a class="NavigationArrow" href="../power_of_introspection/summary.html">&lt;&lt;&nbsp;小结</a></td>
            <td width="30%" align="center"><br>&nbsp;<span class="divider">|</span>&nbsp;<span class="thispage">1</span> <span class="divider">|</span> <a href="importing_modules.html" title="5.2.&nbsp;使用 from module import 导入模块">2</a> <span class="divider">|</span> <a href="defining_classes.html" title="5.3.&nbsp;类的定义">3</a> <span class="divider">|</span> <a href="instantiating_classes.html" title="5.4.&nbsp;类的实例化">4</a> <span class="divider">|</span> <a href="userdict.html" title="5.5.&nbsp;探索 UserDict：一个封装类">5</a> <span class="divider">|</span> <a href="special_class_methods.html" title="5.6.&nbsp;专用类方法">6</a> <span class="divider">|</span> <a href="special_class_methods2.html" title="5.7.&nbsp;高级专用类方法">7</a> <span class="divider">|</span> <a href="class_attributes.html" title="5.8.&nbsp;类属性介绍">8</a> <span class="divider">|</span> <a href="private_functions.html" title="5.9.&nbsp;私有函数">9</a> <span class="divider">|</span> <a href="summary.html" title="5.10.&nbsp;小结">10</a>&nbsp;<span class="divider">|</span>&nbsp;
            </td>
            <td width="35%" align="right"><br><a class="NavigationArrow" href="importing_modules.html">使用 from module import 导入模块&nbsp;&gt;&gt;</a></td>
         </tr>
         <tr>
            <td colspan="3"><br></td>
         </tr>
      </table>
      <div class="Footer">
         <p class="copyright">Copyright © 2000, 2001, 2002, 2003, 2004 <a href="mailto:mark@diveintopython.org">Mark Pilgrim</a></p>
         <p class="copyright">Copyright © 2001, 2002, 2003, 2004, 2005, 2006, 2007 <a href="mailto:python-cn@googlegroups.com">CPyUG (邮件列表)</a></p>
      </div>
   </body>
</html>